package com.wistech.utils;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class ShardedJedisFactory {
	private static final Logger logger = LoggerFactory
			.getLogger(ShardedJedisFactory.class);
	/**
	 * redis连接缓存池
	 */
	private ShardedJedisPool shardedJedisPool;

	/**
	 * 获取redis连接
	 * 
	 * @return conn
	 */
	/**
	 * 获取redis连接
	 * 
	 * @return conn
	 */
	public ShardedJedis getJedis() {
		ShardedJedis jedis = null;
		int times = 0;// 获取连接次数
		int repeats = 2;// 重复次数
		Exception exception = null;
		while (jedis == null) {
			try {
				times++;
				jedis = shardedJedisPool.getResource();
			} catch (Exception e) { // 捕捉异常
				exception = e;
				if (times <= repeats) {
					ThreadUtils.sleep(1000);
				} else {
					break;
				}
			}
		}
		if (jedis == null) {
			logger.error("get jedist from jedis pool error.", exception);
		}
		return jedis;
	}

	/**
	 * 销毁连接缓冲池
	 */
	public void destroyJedisPool() {
		if (shardedJedisPool != null) {
			logger.info("destroy jedis pool.");
			shardedJedisPool.destroy();
			shardedJedisPool = null;
		}
	}

	/**
	 * 释放redis连接
	 * 
	 * @param conn
	 */
	public void returnJedis(ShardedJedis jedis) {
		if (null != jedis) {
			try {
				shardedJedisPool.returnResource(jedis);
			} catch (Exception e) {
				logger.error("return jedist to jedis pool error.", e);
			}
		}
	}

	/**
	 * 设置连接池
	 * 
	 */
	public void setShardedJedisPool(ShardedJedisPool shardedJedisPool) {
		this.shardedJedisPool = shardedJedisPool;
	}

	/**
	 * @return the shardedJedisPool
	 */
	public ShardedJedisPool getShardedJedisPool() {
		return shardedJedisPool;
	}

	public static String serialize(Object obj) {
		return JSON.toJSONString(obj, SerializerFeature.WriteClassName);
	}

	@SuppressWarnings("unchecked")
	public static <T> T deserialize(String json) {
		if (StringUtils.isBlank(json)) {
			return null;
		}
		return (T) JSON.parse(json);
	}
}
